<?php
/**
 * 新闻服务类
 */
namespace app\index\service;
use Config;
use Cache;
use think\Db;
use think\Model;
class News 
{
	/**
	 * 地产主页
	 */
	public function index()
	{
      return '新闻首页';
	}

	//获取新闻列表
	public function getMainNewsIndex($type='imgtext',$prarm,$page,$page_size){
		$prarm = !empty($prarm) ? $this->getWhere($prarm) : '';
		switch($type){
			case 'imgtext':
				$table = 'zh_news_img_text';
				$modle = new \app\index\model\Imgtext;
				$field = 'id,member_id,member_id as member_name,title,outline,thumb,thumb as thumburl,is_top,create_time,id as comment';
				break;
			case 'video':
				$table = 'zh_news_video';
				$modle = new \app\index\model\Video;
				$field = 'id,member_id,member_id as member_name,title,type,url,thumb,thumb as thumburl,is_top,create_time,id as comment';
				break;
			case 'friend':
			default:
				$table = 'zh_news_friend';
				$modle = new \app\index\model\Friend;
				$field = 'id,nickname,sex,birth as age,type,hobby,thumb,thumb as thumburl,province,city,area,id as comment,city as city_text,province as province_text,area as area_text,sex as sex_name,birth as age,type as mtype,is_top';
				break;
		}
		$db = $modle->where('is_delete=0'.$prarm)->order('is_top DESC,id DESC,sort DESC')->field($field);
		$list = $db->limit(($page-1)*$page_size,$page_size)->select();
		return $list??[];
	}

	//获取新闻详情
	public function getNewsInfo($type='imgtext',$id=0,$member_id){
		$row='';
		switch($type){
			case 'imgtext':
				$i= 1;
				$table = 'zh_news_img_text';
				$modle = new \app\index\model\Imgtext;
				$field = '*,member_id as member_name,thumb as thumburl,member_id as member_nickname,member_id as member_avatar,member_id as sign_text';
				break;
			case 'video':
				$i= 2;
				$table = 'zh_news_video';
				$modle = new \app\index\model\Video;
				$field = '*,type as mtype,member_id as member_name,thumb as thumburl,member_id as member_nickname,member_id as member_avatar,member_id as sign_text';
				break;
			case 'friend':
			default:
				$i= 3;
				$table = 'zh_news_friend';
				$modle = new \app\index\model\Friend;
				$field = '*,city as city_text,province as province_text,area as area_text,sex as sex_name,birth as age,type as mtype,thumb as thumburl,member_id as member_nickname,member_id as member_avatar,member_id as sign_text';
				break;
		}
		$row = $modle->field($field)->get($id);
		$row = $row?$row->toArray():[];
		$row['comment'] = $this->getCommontList($row['id']??0,'list');
		$row['commentCount'] = $this->getCommontCount($row['id']??0,$i-1);
		$row['is_follow'] = $this->getFollowInfo($row['member_id'],$member_id);
		$row['is_collection'] = $this->getCollectionnews($row['id'],$member_id);
		$row['is_dianzan'] = $this->getDianzannews($row['id'],$member_id);
		return $row;
	}
	public function getCollectionnews($news_id,$member_id){
		if(!$member_id){
			return ['code'=>0,'msg'=>'未收藏'];
		}else{
			$where['member_id']=$member_id;
		}
		$where['news_id']=$news_id;
		$modle = new \app\index\model\Newscollect;
		$res=$modle->where($where)->find();
		if($res){
			return ['code'=>0,'msg'=>'已收藏'];
		}else{
			return ['code'=>0,'msg'=>'未收藏'];
		}
	}
	public function getDianzannews($news_id,$member_id){
		if(!$member_id){
			return ['code'=>0,'msg'=>'未点赞'];
		}else{
			$where['member_id']=$member_id;
		}
		$where['news_id']=$news_id;
		$modle = new \app\index\model\Newspraise;
		$res=$modle->where($where)->find();  
		if($res){
			return ['code'=>1,'msg'=>'已点赞'];
		}else{
			return ['code'=>0,'msg'=>'未点赞'];
		}
	}
	//获取评论列表
	public function getCommontList($wid,$type='conut'){
		$modle = new \app\index\model\Common;
		switch ($type) {
			case 'conut':
				$result = $modle->countData(['news_id'=>$wid??0])??0;
				break;
			case 'list':
				$result = $modle->fetchAll(['news_id'=>$wid??0],'*,member_id as member_nickname,member_id as member_avatar,member_id as sign_text,create_time as create_time_text,FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%s") as create_time','create_time DESC')??[];
				break;
			default:
				$result = $modle->fetch(['id'=>$wid??0,'*,member_id as member_nickname,member_id as member_avatar,member_id as sign_text'])??[];//评论ID
				break;
		}
		return $result;
	}
	//获取评论数量
	public function getCommontCount($wid,$type=0){
		$modle = new \app\index\model\Common;
		$where['news_id']=$wid;
		$where['type']=$type;
		$result=$modle->where($where)->count();
		return $result;
	}
	//提交函数
	public function saveNewsInfo($type="imgtext",$prarm=[]){
		//return $this->errorReturn('','XX错误');
		switch($type){
			case 'imgtext':
				$table = 'zh_news_img_text';
				$modle = new \app\index\model\Imgtext;
				break;
			case 'video':
				$table = 'zh_news_video';
				$modle = new \app\index\model\Video;
				break;
			case 'friend':
			default:
				$table = 'zh_news_friend';
				$modle = new \app\index\model\Friend;
				break;
		}

		if($prarm['type']??true){
			$prarm['type']= 0;
			if($prarm['mtype']??true){
				$prarm['type'] = $prarm['mtype'];
			}
		}

		if($prarm['thumb']??true){
			$prarm['thumb'] = (parse_url($prarm['thumb'])['path'])??$prarm['thumb'];
		}

		if(empty($prarm['id'])){
			//添加
			$prarm['create_time'] = $prarm['update_time'] = time();
			return $modle->allowField(true)->save($prarm)??0;
		}else{
			//修改
			$prarm['update_time'] = time();
			return $modle->allowField(true)->save($prarm,['id'=>$prarm['id']])??0;
		}
	}

	/**
	 * 支付函数
	 * @param  int $type 支付种类
	 * @return SQLwhere条件    
	 */
	public function payNewsPrice($type="imgtext",$prarm=[])
	{
		switch($type){
			case 'imgtext':
				$table = 'zh_news_img_text_order';
				$prefix = 'YJN';
				$modle = new \app\index\model\Imgtextorder;
				break;
			case 'video':
				$table = 'zh_news_video_order';
				$prefix = 'YJV';
				$modle = new \app\index\model\Videorder;
				break;
			case 'friend':
			default:
				$table = 'zh_news_friend_order';
				$prefix = 'YJF';
				$modle = new \app\index\model\Friendorder;
				break;
		}
		$memObj = new \app\index\model\Members;
		//数据验证
		
		//入库数据
		$m['order_sn'] = $prefix.date('YmdHis').rand('100000','999999');
		$m['member_id'] = $prarm['member_id'];
	    $m['news_id'] = $prarm['news_id']??0;
	    $m['total_amount'] = $prarm['total_amount']??0.00;
	    $m['pay_type'] = $prarm['pay_type']??1;
	    $m['status'] = 0;
	    $m['create_time'] = time();
		//事务处理
		Db::startTrans();
		try{
			$paymemt = [];
			//创建订单
			$rew = $modle::create($m);
			if(!$rew){
                Db::rollback();
                exception('创建订单失败');
            }

			if ($m['pay_type'] == 1) {
                //微信支付
                Db::rollback();
            	exception('微信支付接口正在开发中.....');
            } elseif ($m['pay_type'] == 2) {
                //支付宝支付
                Db::rollback();
            	exception('支付宝支付接口正在开发中.....');
            } elseif ($m['pay_type'] == 3) {
            	//金币支付
            	$gold = $memObj->get(['member_id'=>$prarm['member_id']??0])->value('gold');//账户余额

            	if(floatval($gold)< floor($m['total_amount'])){
            		Db::rollback();
            		exception('金币不足');
            	}

                $memberOk = $memObj::where(['member_id'=>$prarm['member_id']])->update(['gold' =>($gold - floor($m['total_amount']))]);
                if(!$memberOk){
                    Db::rollback();
                    exception('更新用户金币失败');
                }
            }else{
            	//钱包支付
            	$account = $memObj->get(['member_id'=>$prarm['member_id']??0])->value('account');//账户余额
            	if ($account < $m['total_amount']) {
                    Db::rollback();
                    exception('余额不足');
                }
                $memberOk = $memObj::where(['member_id'=>$prarm['member_id']])->update(['gold' =>($account - $m['total_amount'])]);
                if(!$memberOk){
                    Db::rollback();
                    exception('更新账户余额失败');
                }
            }
            $orderOk = $modle->where(['id'=>$rew->id])->update(['status' => 2,'update_time' => time(),'pay_time'=> time()]);

            if(!$orderOk){
                Db::rollback();
                exception('更新订单支付状态失败');
            }
            Db::commit();
            return ['status'=>1,'paymemt'=>$paymemt];
		}catch (\Exception $e){
			Db::rollback();
			return ['status'=>0,'msg'=>$e->getMessage()];
		}
	}

	/**
	 * 提交评论
	 * @param  int $type 		新闻类型
	 * @param  int $news_id 	新闻ID
	 * @param  int $member_id 	用户ID
	 * @param  int $comment_id 	上级评论ID 
	 * @return array 评论状态
	 */
	public function saveCommentInfo($type=0,$prarm=[]){
		//数据验证
		$msg = '发表失败';
		$code = 0;
		$commentObj = model('app\index\model\Comment');
		$prarm['create_time']=$prarm['update_time']=time();
		if($commentObj::create($prarm)){
			$msg = '发表成功';
			$code = 1;
		};
		return ['status'=>$code,'msg'=>$msg];
	}

	/**
	 * 评论点赞
	 * @param int $id 评论ID
	 * @return array 状态、提示信息
	 */
	public function savechangeGood($id=0,$member_id=0)
	{
		$commentObj = model('app\index\model\Comment');
		$praiseObj  = model('app\index\model\Praise');
		Db::startTrans();
        try{
        	//评论表中数据
        	$ppid = $commentObj::alias('co')->join('praise p','p.comment_id=co.id')->where(['p.comment_id'=>$id,'p.member_id'=>$member_id])->value('p.id');

        	if(!$ppid){
        		$praiseObj::create(['comment_id'=>$id,'member_id'=>$member_id,'create_time'=>time()]);//添加点赞数据
        		$commentObj::where('id',$id)->setInc('like_num',1);//评论列表点赞数+1
        		$msg = '点赞成功';
        		$val = 1;
        	}else{
        		$praiseObj::destroy($ppid);//删除点赞数据
        		$commentObj::where('id',$id)->setDec('like_num',1);//评论列表点赞数-1
        		$msg = '取消成功';
        		$val = 0;
        	}
            //提交事务
            Db::commit();
            return ['status'=>$val,'msg'=>$msg];
        } catch (PDOException $e) {
            Db::rollback();
           return ['status'=>'-1','msg'=>'点赞失败！'.$e->getMessage()];
        }  catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            return ['status'=>'-1','msg'=>'点赞失败！'.$e->getMessage()];
        }
	}


	/**
	 * 关注列表
	 * @param  int $type 		新闻类型
	 * @param  int $news_id 	新闻ID
	 * @param  int $member_id 	用户ID
	 * @param  int $gh 			列表
	 * @return array 列表数据
	 */
	public function followList($type='imgtext',$prarm=[]){
		//数据验证
		$member_id = $prarm['member_id']??0;//用户ID
		$type      = $type??'imgtext';
		$key = 'follow'.'_'.$type.'_'.$member_id;
		$Cache = Cache::store('redis')->handler();
		if(!$Cache->exists($key)){
			return ['code'=>1,'msg'=>'获取失败','data'=>[]];
		}else{
			$list = $Cache->lrange($key,0,-1);
			return ['code'=>1,'msg'=>'获取成功','data'=>$list];
		}
	}

	/**
	 * 获取关注信息
	 * @param  int $type 		新闻类型
	 * @param  int $member_id 	用户ID
	 * @return array 添加状态
	 */
	public function getFollowInfo($news_member_id,$member_id){
		if(!$member_id){
			return ['code'=>0,'msg'=>'未关注'];
		}else{
			$where['member_id'] =$member_id;
		}
		$where['follow_member_id'] =$news_member_id;
		$Newsfollow = model('app\index\model\Newsfollow');
		$res=$Newsfollow->where($where)->find();
		if($res){
			return ['code'=>1,'msg'=>'已关注'];
		}else{
			return ['code'=>0,'msg'=>'未关注'];
		}
	}
	/**
	 * 添加关注
	 * @param  int $type 		新闻类型
	 * @param  int $member_id 	用户ID
	 * @return array 添加状态
	 */
	public function saveFollowInfo($type='imgtext',$prarm=[]){

		$id = $prarm['id']??0;//新闻ID
		$member_id = $prarm['member_id']??0;//用户ID
		$type      = $type??'imgtext';
		$status    = $prarm['status']??0;// 默认取消关注 , [1关注 ， 0 取消关注]
		$Cache = Cache::store('redis')->handler();
		
		if(empty($id)||empty($member_id)||empty($type)){
			return ['status'=>0,'msg'=>'参数不完整'];
		}

		//换成Hash
		$key = 'follow'.'_'.$type.'_'.$id.'_'.$member_id;
		$klist = 'follow'.'_'.$type.'_'.$member_id;
		if($status==1){
			//关注
			if(!$Cache->exists($key)){
				$Cache->lPush($klist,serialize(['member_id'=>$member_id,'type'=>$type,'id'=>$id,'time'=>time()]));
				$Cache->lPush($key,1);
				return ['status'=>1,'msg'=>'关注成功'];
			}
			return ['status'=>0,'msg'=>'你已关注'];
		}else{
			//取消关注
			$sharr = [];
			$Cache->del($key);
			$Cache->del($klist);
			if($list = $Cache->lrange($klist,0,-1)){
				foreach($list as $k=>$v){
					$sharr = unserialize($v);
					if($sharr['id']==$id){
						$Cache->lrem($klist,$list[$k],0);
					}
				}
			}
			return ['status'=>0,'msg'=>'取消成功'];
		}
	}

	/**
	 * 查询条件函数
	 * @param  array $prarm  查询条件必须是数组
	 * @return SQLwhere条件    
	 */
	private function getWhere($prarm=[])
    {
		$where = '';
		$where .= !empty($prarm['id'])? ' and id='.$prarm['id']:'';
		$where .= !empty($prarm['member_id'])? ' and member_id='.$prarm['member_id']:'';
		$where .= !empty($prarm['title'])? ' and title like \'%'.trim($prarm['title']).'%\'':'';
		$where .= !empty($prarm['outline'])? ' and outline like \'%'.trim($prarm['outline']).'%\'':'';
		$where .= !empty($prarm['create_time'])? ' and create_time='.$prarm['create_time']:'';
		$where .= !empty($prarm['is_delete'])? ' and is_delete='.$prarm['is_delete']:'';
		$where .= !empty($prarm['is_top'])? ' and is_top='.$prarm['is_top']:'';
		$where .= !empty($prarm['nickname'])? ' and nickname like \'%'.trim($prarm['nickname']).'%\'':'';
		$where .= !empty($prarm['hobby'])? ' and hobby like \'%'.trim($prarm['hobby']).'%\'':'';
		$where .= !empty($prarm['address'])? ' and address like \'%'.trim($prarm['address']).'%\'':'';
		$where .= !empty($prarm['province'])? ' and province='.$prarm['province']:'';
		$where .= !empty($prarm['city'])? ' and city='.$prarm['city']:'';
		$where .= !empty($prarm['area'])? ' and area='.$prarm['area']:'';
		return $where;
	}
	/*
	关注
	*/
	public function newsFollow($data){
		$Newsfollow = model('app\index\model\Newsfollow');
		$res=$Newsfollow->where($data)->find();
		if($res){
			$result=$Newsfollow->where($data)->delete();
			if($result){
				return ['status'=>2,'msg'=>'取消关注'];			
			}else{
				return ['status'=>0,'msg'=>'操作失败'];	
			}
		}else{
			$result=$Newsfollow->save($data);
			if($result){
				return ['status'=>1,'msg'=>'关注成功'];	
			}else{
				return ['status'=>0,'msg'=>'操作失败'];	
			}
		}
	}
	/**新闻点赞***/
	public function newsGivegood($news_id,$member_id){
		$Newspraise = model('app\index\model\Newspraise');
		$data['news_id']=$news_id;
		$data['member_id']=$member_id;
		$res=$Newspraise->where($data)->find();
		if($res){
			$result=$Newspraise->where($data)->delete();
			if($result){
				return ['status'=>1,'msg'=>'取消点赞'];	
			}else{
				return ['status'=>0,'msg'=>'操作失败'];	
			}
		}else{
			$result=$Newspraise->save($data);
			if($result){
				return ['status'=>1,'msg'=>'点赞成功'];	
			}else{
				return ['status'=>0,'msg'=>'操作失败'];	
			}
		}
	}
}